const Base = require('./base.js');

module.exports = class extends Base {
    // async __before() {
    //     // await this.checkAccessPermission('manage_account', '用户不能维护系统后台管理员帐号', true);
    // }

    async indexAction() {
        // const Model = this.mongoose('Module');
        // const modules = await Model.find().exec();
        // // console.log(modules);
        //
        // let list = [{key:'admin',title:'admin'}];
        // for (let item of modules) {
        //     list.push({
        //         key: item.name,
        //         title: item.alias,
        //     })
        // }
        // this.assign({
        //         modules: list
        //     }
        // );
        await this.display('admin/role/index');
    }

    async tableAction() {

        const p = this.query('page') || 1;
        const id = this.post('id');
        // const module = this.post('module');
        const keywords = this.post('keywords');

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {username: {$regex: keywords, $options: "$i"}},
                    {email: {$regex: keywords, $options: "$i"}},
                    {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        // //等值查询
        // if (module !== "") {
        //     queryParams = Object.assign(queryParams, {module: module});
        // }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: think.Mongoose.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error(1001, '没找到符合条件的记录');
                return;
            }
        }

        const Model = this.mongoose('Role', {}, 'admin');
        const pageSize = this.mongoose('Config', {}, 'admin').C('LIST_ROWS');
        const pageEntity = await Model.findPage({
            page: p,
            pageSize: pageSize
        }, 'permissions parent', queryParams, {}, {username: 'asc'});

        this.assign({
            records: pageEntity.data,
            pager: super.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });

        await this.display('admin/role/table');
    }

    async deleteAction() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.mongoose('Role');
        for (const i of ids) {
            // await Model.findUserByIdAndRemove(i);//删除关联数据
        }
        this.success('/admin/role/index', '删除成功');
    }

    async addAction() {

        if (this.isPost()) {

            const administrator = this.post();

            if (administrator.password) {
                administrator.password = md5(administrator.password);
            } else {
                delete administrator.password;
            }

            this.mongoose('Administrator').saveOrUpdate(administrator);

            this.json('/admin/administrator/index', '保存成功');

        } else {

            if (this.query('id')) {
                const administrator = await this.mongoose('Administrator').findOne({_id: this.query('id')}).exec();
                this.assign({administrator: administrator});
                await this.display('admin/administrator/add');
            } else {
                await this.display('admin/administrator/add');
            }
        }
    }

    async menuInRoleAction() {

        if (this.isPost) {

            const post = this.post();

            const rules = post.rules || [];
            const roleId = post.roleId;

            const RoleMenu = this.mongoose('RoleMenu', {}, 'admin');
            await RoleMenu.remove({roleId: roleId}).exec();

            for (let rule of rules) {
                // console.log(rule);
                await RoleMenu.authMenuForRole(roleId, rule);
            }

            // console.log(post);

        } else {

            const roleId = this.query('roleId');
            const Menu = this.mongoose('Menu', {}, 'admin');
            const MenuRole = this.mongoose('RoleMenu', {}, 'admin');

            const modules = await Menu.distinct('module').lean().exec();


            // console.log(modules);
            // console.log(typeof modules);

            let authedMenus = await MenuRole.find({roleId: roleId}).exec();

            // console.log(authedMenus);

            let data = [];
            for (let m of modules) {
                let menus = await Menu.find({module: m}).exec();

                let items = [];

                for (let menu of menus) {
                    let item = {
                        id: menu._id,
                        title: menu.title,
                        authed: false,
                    };

                    for (let authedMenu of authedMenus) {
                        if (authedMenu.menuId.toString() === menu._id.toString()) {
                            item.authed = true;
                            break;
                        }
                    }

                    items.push(item);
                }
                data.push({
                    module: m,
                    items: items
                });
            }

            // console.log(data);

            this.assign({
                roleId: roleId,
                records: data
            });

            this.display('admin/role/menuInRole');
        }
    }
};